#include "apue.h"
#include "sys/wait.h"

void lock(char * title, int fp) {
    if (writew_lock(fp, 0, SEEK_SET, 1) < 0)
        err_sys("writew_lock error");
    printf("%s got write lock\n", title);
}
void unlock(char *title, int fp) {
    if (un_lock(fp, 0, SEEK_SET, 1) < 0)
        err_sys("unlock error");
    printf("%s unlock write lock\n", title);
}

int main() {
    int fd;
    pid_t pid;
    if ((fd= open("tmpfile", O_RDWR|O_TRUNC|O_CREAT, FILE_MODE)) < 0)
        err_sys("open error");
    if (write(fd, "ab", 2) < 0)
        err_sys("write error");
    lock("parent", fd);

    if ((pid= fork()) < 0)
        err_sys("fork error");
    if (pid > 0) {  // parent
        printf("parent sleep 10 second.\n");
        sleep(10);
        unlock("parent", fd);
        if (waitpid(pid, NULL, 0) < 0)
            err_sys("waitpid error");
        printf("end\n");

    } else {    // child
        lock("child", fd);
        printf("child sleep 2 second.\n");
        sleep(2);
        printf("child end\n");
    }
    exit(0);
}
